<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>城市联动并存入后台</title>

</head>
<body>

    <select>
        <option value="0">--请选择省份--</option>
        {% for v in citylist  %}
            <option value="{{ v.id }}">
                {{ v.name }}
            </option>
        {% endfor  %}
    </select>

</body>
</html>
<script src="/static/js/jquery-2.1.1.js"></script>
<script>
     $('select').on('change',function () {

            id = $(this).val();
            var data = {
                'id':id
            };

            // 获取省份信息
            prov = $('select').find('option')[id].text

            // console.log( prov )

            $(this).nextAll('select').remove();

            jqueryAjax( data );

        });

    function jqueryAjax ( data ) {

        $.ajax({
                url:"http://127.0.0.1:8999/api/getcity",
                type:"POST",
                dataType:"json",
                data:data,
                success:function (res) {

                    if ( res.code == 200 ){
                        var citys = res.data;
                        //去除后缀
                        if( citys.length == 0 ){ return };

                        var sel = $('<select></select>');

                        ops = '<option value = "0">--请选择城市--</option>';

                        for ( var i = 0 ; i < citys.length;i++){

                            ops += '<option value="'+citys[i]['id']+'">'+citys[i]['name']+'</option>'
                        }

                        sel.html( ops );

                        $('body').append(sel);

                        $('select').on('change',function ( ) {

                            id = $(this).val();

                            var data = {

                                'id':id
                            };

                            //调用获取地址方法 
                            adrs = prov +  mergeAdress( citys,data);



                            console.log( adrs )  
  
                            $(this).nextAll('select').remove();

                            jqueryAjax( data );

                        })
                    }

                }
            })
    };

    // 定义空字符串
    var adr = '';        
    // 拼接地址
    function mergeAdress(citys=null,data=null){

        // 获取地址信息
        for( var i =0; i<citys.length;i++){

            if( citys[i]['id'] ==  Number(data['id'])){

              adr += (citys[i]['name'])      

            }

        };
        return  adr ;

    }


</script>
